# -*- coding: utf-8 -*-
from flask import Blueprint,jsonify,request,redirect
from common.libs.Helper import ops_render,getCurrentDate,iPagination,getDictFilterField
from common.libs.UrlManager import UrlManager
from application import db,app
from common.models.food.FoodCat import FoodCat
from common.models.food.Food import Food
from decimal import Decimal
from common.models.food.FoodStockChangeLog import FoodStockChangeLog
from sqlalchemy import or_
from common.libs.food.FoodService import FoodService

route_food = Blueprint( 'food_page',__name__ )

@route_food.route( "/index",methods = [ 'GET','POST'] )
def index():
    resp_data = {}
    req = request.values
    page = int(req['p']) if ('p' in req and req['p']) else 1
    query = Food.query
    if 'mix_kw' in req:
        # 查询名称和描述
        rule = or_(Food.name.ilike("%{0}%".format(req['mix_kw'])), Food.tags.ilike("%{0}%".format(req['mix_kw'])))
        query = query.filter(rule)

    # 查询状态值
    if 'status' in req and int(req['status']) > -1:
        query = query.filter(Food.status == int(req['status']))

    # 通过分类id查询分类
    if 'cat_id' in req and int(req['cat_id']) > 0:
        query = query.filter(Food.cat_id == int(req['cat_id']))

    # 分页 ：总数量 分销大小 总数量 希望展示的东西
    page_params = {
        'total': query.count(),
        'page_size': app.config['PAGE_SIZE'],
        'page': page,
        'display': app.config['PAGE_DISPLAY'],
        'url': request.full_path.replace("&p={}".format(page), "")
    }
    # iPagination 获得分页参数
    pages = iPagination(page_params)
    offset = (page - 1) * app.config['PAGE_SIZE']
    # 取出所有数据
    list = query.order_by(Food.id.desc()).offset(offset).limit(app.config['PAGE_SIZE']).all()

    # 快速将我们查询的结果集按照某一个字段构建成一个字典
    # key值是我们的id自增字段
    cat_mapping = getDictFilterField( FoodCat,FoodCat.id,"id",[] )
    resp_data['list'] = list
    resp_data['pages'] = pages
    resp_data['search_con'] = req
    resp_data['status_mapping'] = app.config['STATUS_MAPPING']
    resp_data['cat_mapping'] = cat_mapping
    resp_data['current'] = 'index'
    return ops_render("food/index.html", resp_data)

@route_food.route( "/info",methods = [ 'GET','POST'] )
def info():
    resp_data = {}
    req = request.args
    id = int(req.get("id", 0))
    reback_url = UrlManager.buildUrl("/food/index")

    if id < 1:
        return redirect(reback_url)

    info = Food.query.filter_by(id=id).first()
    if not info:
        return redirect(reback_url)

    stock_change_list = FoodStockChangeLog.query.filter(FoodStockChangeLog.food_id == id).order_by(FoodStockChangeLog.id.desc()).all()

    resp_data['info'] = info
    resp_data['stock_change_list'] = stock_change_list
    resp_data['current'] = 'index'
    return ops_render("food/info.html", resp_data)


@route_food.route( "/set" ,methods = [ 'GET','POST'] )
def set():
    if request.method == "GET":
        # 在页面传送过来的时候，取得id字段
        resp_data ={}
        req = request.args
        id =int(req.get('id',0))
        info = Food.query.filter_by(id=id).first()
        if info and info.status !=1:
            return redirect(UrlManager.buildUrl("/food/index"))

        cat_list=FoodCat.query.all()# 分类
        resp_data['info'] = info
        resp_data['cat_list'] = cat_list
        resp_data['current'] = 'index'
        return ops_render( "food/set.html",resp_data )
    # 从前端传值过来
    resp ={'code':200,'msg':'操作成功','data':{}}
    req = request.values
    id = int(req['id']) if 'id' in req and req['id'] else 0
    cat_id = int(req['cat_id']) if 'cat_id' in req else 0
    name = req['name'] if 'name' in req else ''
    price = req['price'] if 'price' in req else ''
    main_image = req['main_image'] if 'main_image' in req else ''
    summary = req['summary'] if 'summary' in req else ''
    stock = int(req['stock']) if 'stock' in req else ''
    tags = req['tags'] if 'tags' in req else ''

    if cat_id <1:
        resp['code']=-1
        resp['msg']="请选择分类"
        return jsonify(resp)

    if name is None or len(name) <1:
        resp['code'] =-1
        resp['msg'] ="请输入符合规范的名称"
        return jsonify(resp)

    price = Decimal(price).quantize(Decimal('0.00'))
    if price <= 0:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的售卖价格"
        return jsonify(resp)

    if main_image is None or len(main_image) <3:
        resp['code'] =-1
        resp['msg'] ="请上传封面图片"
        return jsonify(resp)

    if summary is None or len(summary) <3:
        resp['code'] =-1
        resp['msg'] ="请输入具体描述，并且不能少于10个字符"
        return jsonify(resp)

    if stock < 1:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的库存量"
        return jsonify(resp)

    if tags is None or len(tags) <1:
        resp['code'] =-1
        resp['msg'] ="请输入标签，便于搜索"
        return jsonify(resp)
    # 库存量
    food_info = Food.query.filter_by(id =id ).first()
    before_stock =0
    # 存在就更新操作
    if food_info:
        model_food =food_info
        before_stock=model_food.stock
    #     不存在就插入
    else:
        model_food=Food()
        model_food.status= 1
        model_food.created_time=getCurrentDate()

    model_food.cat_id = cat_id
    model_food.name = name
    model_food.price = price
    model_food.main_image = main_image
    model_food.summary = summary
    model_food.stock = stock
    model_food.tags = tags
    model_food.updated_time = getCurrentDate()

    db.session.add(model_food)
    ret = db.session.commit()

    FoodService.setStockChangeLog( model_food.id,int(stock) - int(before_stock),"后台修改" )
    return jsonify(resp)

@route_food.route( "/cat" )
def cat():
    # 查询所有结果集:分类列表信息
    resp_data = {}
    req = request.values
    query = FoodCat.query

    # 对status进行统一处理
    if 'status' in req and int(req['status'])>-1:
        query=query.filter(FoodCat.status ==int(req['status']))

    # 先按照权重排列字段，再按照id排列分信息  .all()取得所有信息进行展示
    list =query.order_by( FoodCat.weight.desc(),FoodCat.id.desc()).all()
    resp_data['list']=list
    # 将网页的search_con参数回传到后端  ：search_con=请求参数
    resp_data['search_con']=req
    resp_data['status_mapping']=app.config['STATUS_MAPPING']
    resp_data['current'] = 'cat'
    return ops_render( "food/cat.html",resp_data )

# post 数据提交 get数据展示
@route_food.route( "/cat-set",methods = [ "GET","POST" ] )
def catSet():
    # 添加分类
    if request.method == "GET":
        resp_data = {}
        req = request.args
        id = int(req.get("id", 0))
        info = None
        if id:
            info = FoodCat.query.filter_by( id = id ).first()
        resp_data['info'] = info
        resp_data['current'] = 'cat'
        return ops_render( "food/cat_set.html" ,resp_data )

    # 取出所有值
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values
    # 三元表达式  判断是否在字典中 从网页传过来的值
    id = req['id'] if 'id' in req else 0
    name =req['name'] if 'name' in req else ''
    weight =int(req['weight']) if ('weight' in req and int(req['weight']) >0 ) else 1
    # 参数判断
    if name is None or len(name) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的分类名称~~"
        return jsonify(resp)
    # 查询id是否是存在的
    food_cat_info =FoodCat.query.filter_by( id = id).first()
    # 如果存在则为编辑，如果不存在就是写入
    if food_cat_info:
        model_food_cat = food_cat_info
    else:
        model_food_cat = FoodCat()
        model_food_cat.created_time =getCurrentDate()
    model_food_cat.name =name
    model_food_cat.weight = weight
    model_food_cat.updated_time=getCurrentDate()

    db.session.add(model_food_cat)
    db.session.commit()
    return jsonify(resp)

# 定义一个ops方法  支持post提交
@route_food.route("/cat-ops",methods=["POST"])
def catOps():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values

    # 三元表达式  判断是否在字典中
    id = req['id'] if 'id' in req else 0
    act = req['act'] if 'act' in req else ''

    # 判断id是否存在
    if not id :
        resp['code'] = -1
        resp['msg'] = "请选择要操作的账号!"
        return jsonify(resp)

    # 判断动作是否在 删除或者恢复的操作李里面
    if act not in ['remove','recover']:
        resp['code'] = -1
        resp['msg'] = "操作有误，请重试"
        return jsonify(resp)

    # 判断用户id是否存在
    food_cat_info =FoodCat.query.filter_by(id=id).first()
    if not food_cat_info:
        resp['code'] = -1
        resp['msg'] = "指定分类不存在！"
        return jsonify(resp)

    # 根据动作判断  如果你的动作 等于 删除动作  那么就让status字段等于0即可
    if act =="remove":
        food_cat_info.status = 0
    elif act=="recover":
        food_cat_info.status = 1
    # 每一次更新的时候 要更新update_time字段 来将时间进行更新
        food_cat_info.update_time =getCurrentDate()
    db.session.add(food_cat_info)
    db.session.commit()
    return jsonify(resp)


@route_food.route("/ops",methods=["POST"])
def ops():
    resp = { 'code':200,'msg':'操作成功~~','data':{} }
    req = request.values

    id = req['id'] if 'id' in req else 0
    act = req['act'] if 'act' in req else ''

    if not id :
        resp['code'] = -1
        resp['msg'] = "请选择要操作的账号~~"
        return jsonify(resp)

    if act not in [ 'remove','recover' ]:
        resp['code'] = -1
        resp['msg'] = "操作有误，请重试~~"
        return jsonify(resp)

    food_info = Food.query.filter_by( id = id ).first()
    if not food_info:
        resp['code'] = -1
        resp['msg'] = "指定美食不存在~~"
        return jsonify(resp)

    if act == "remove":
        food_info.status = 0
    elif act == "recover":
        food_info.status = 1

    food_info.updated_time = getCurrentDate()
    db.session.add(food_info)
    db.session.commit()
    return jsonify( resp )
